const express = require("express");
const path = require("path");
const cors = require("cors");
const app = express();
const bodyParser = require("body-parser");
const appConfig = require(path.resolve(__dirname, "./config/setting.js"));
const requireContext = require("./config/requireContext");
const { expressjwt: jwt } = require("express-jwt");
const { ValidationError } = require("express-validation");
require('./setDefaultConfig.js')
// 解析json形式的数据
app.use(bodyParser.json());
// 解析 application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }));
appConfig.cors && app.use(cors());

// 注册全局中间件
app.use((req, res, next) => {
  res.cc = (err, code = 500) => {
    res.send({
      code,
      msg: err instanceof Error ? err.message : err
    });
  };
  next();
});

// 配置需要身份验证的请求
app.use(
  jwt({ secret: appConfig.tokenSecretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/(entry|static)/]
  })
);


//挂载静态资源
app.use("/static", express.static(path.resolve(__dirname, "/static")));

// 导入路由模块
const routerFileList = requireContext(path.resolve(__dirname, "./router"));
routerFileList.forEach((v) => {
  app.use(`/${v.filename}`, require(`${v.fileUrl}`));
});

// 错误处理机制
app.use((err, req, res, next) => {
	if (err instanceof ValidationError) {
	  res.status(400).send({
		code: process.env.failCode,
		msg: "参数校验失败",
		data: err.details,
	  });
	} else if (err.name == "UnauthorizedError") {
	  res.status(401).send({
		code: process.env.failCode,
		msg: "身份验证失败，请重新登录",
	  });
	} else {
	  res.status(400).send({
		code: process.env.failCode,
		err,
	  });
	}
  });
  

app.listen(appConfig.port, () => {
  console.log(`running ${appConfig.host}:${appConfig.port}`);
});
